package com.killer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.killer.dao.AuthCodeMapper;
import com.killer.pojo.AuthCode;
import com.killer.rpc.EmailServiceFeign;
import com.killer.service.CodeService;
import com.killer.util.CodeUtil;
import com.killer.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author ：Killer
 * @date ：Created in 20-12-31 下午3:46
 * @description：${description}
 * @modified By：
 * @version: version
 */
@Service
public class CodeServiceImpl implements CodeService{

    @Autowired
    private AuthCodeMapper authCodeMapper;
    @Autowired
    private EmailServiceFeign emailServiceFeign;

    @Override
    public void generateCode(String email) {
        //检查是否一分钟内连续请求
        checkSendRecord(email);
        //创建验证码对象，保存进数据库
        AuthCode autCode=saveGenerateCode(email);
        //调用邮件服务将验证码发送到指定邮件
        boolean success = emailServiceFeign.sendCode(email, autCode.getCode());
        if (!success) {
            //发送邮件不成功则抛出异常
            throw new RuntimeException("验证码发送至邮件失败");
        }
    }

    private void checkSendRecord(String email) {
        //查询最近一次的发送记录
        AuthCode authCode = getLastAuthCodeByEmail(email);
        //一分钟内只能发送一次
        if (authCode != null && DateUtil.addMinutes(authCode.getCreatetime(), 1).getTime() > DateUtil.getNow().getTime()) {
            throw new RuntimeException(email+"一分钟内已发送过，请勿重复发送");
        }
    }

    /**
     * 查询该邮件发送的最近一次的验证码记录
     * @param email
     * @return
     */
    @Override
    public AuthCode getLastAuthCodeByEmail(String email) {
        QueryWrapper<AuthCode> queryWrapper = new QueryWrapper<AuthCode>();
        queryWrapper.eq("email", email).orderByDesc("createtime").last("limit 1");
        List<AuthCode> authCodeList = authCodeMapper.selectList(queryWrapper);
        return CollectionUtils.isEmpty(authCodeList) ? null : authCodeList.get(0);
    }

    private AuthCode saveGenerateCode(String email) {
        AuthCode authCode=new AuthCode();
        //验证码6位
        authCode.setCode(CodeUtil.generateCode(6));
        authCode.setEmail(email);
        authCode.setCreatetime(DateUtil.getNow());
        authCode.setExpiretime(DateUtil.addMinutes(authCode.getCreatetime(), 10));
        authCodeMapper.insert(authCode);
        return authCode;
    }
}
